#define _BSD_SOURCE 

#include<netdb.h>
#include"is_seqnum.h"
#define BACKLOG 50

int main(int argc , char ** argv)
{
    if(argc < 2 || strcmp("--help",argv[1]) == 0) 
        usageErr("%s server-host [sequence-len]\n", argv[0]);
    // 调用getaddrinfo 获取一组适合连接到绑定在指定主机上的tCP服务器的socket地址结构
    struct addrinfo hints ;
    memset(&hints,0,sizeof(struct addrinfo));
    hints.ai_canonname = NULL;
    hints.ai_addr = NULL;
    hints.ai_next = NULL;
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_NUMERICSERV;
    // 端口号为PORT_NUM
    struct addrinfo *result,* rp;
    if(getaddrinfo(argv[1] , PORT_NUM ,&hints,&result) != 0)
        errExit("getaddrinfo");

    //遍历socket地址 直到找到一个能够成功用来创建并连接到服务器的地址为止
    int cfd;
    for( rp = result ;rp != NULL; rp = rp -> ai_next){
        cfd = socket(rp->ai_family , rp->ai_socktype,rp->ai_protocol);
        if(cfd == -1)
            continue;
        if(connect(cfd,rp->ai_addr, rp->ai_addrlen) != -1)
            break ;
        close(cfd);
    }
    if(rp == NULL)
        fatal("Could not connect socket to any address");
    freeaddrinfo(result);

    // 发送一个整数指定客户端所需要的序号长度，这个整数将被编码为以换行符结尾的字符串 
    char *reqLenStr = (argc > 2) ? argv[2] : "1";
    if(write(cfd , reqLenStr,strlen(reqLenStr)) != strlen(reqLenStr))
        fatal("Partial/failed write (reqlenStr");
    if(write(cfd,"\n",1) != 1)
        fatal("Partial/failed write (newline)");
    char seqNumStr[INT_LEN];
    int numRead = readLine(cfd , seqNumStr , INT_LEN);

    // 读取服务器发送回来的序号（也以换行符结尾），并将其打印到标准输出上

    if(numRead == -1)
        errExit("readline");
    if(numRead == 0)
        fatal("Unexpected EOF from server");
    printf("Sequence number : %s", seqNumStr);
    return 0;
}